<template>
    <div class="score-page">
        <div class="title1">
            <div class="p1">评分对象</div>
            <div class="p2">
                <a-cascader placeholder="部门或员工"
                    :options="deptList"
                    :load-data="loadData"
                    change-on-select
                    @change="onDeptChange"
                />
            </div>
        </div>
        <div class="container">
            <div class="title">
                <div class="p1">评分类别</div>
                <div class="p2">评分描述</div>
                <div class="p3">单项总分</div>
                <div class="p3">打分</div>
            </div>
            <div class="title" v-for="(item, index) in scoreTypeList" :key="index">
                <div class="p1">
                    <!-- <a-select placeholder="请选择评分类别"
                        style="width: 100%;"
                        :value="item.scoredId||'请选择评分类别'"
                        @change="val => onRuleTypeChange(val, index)"
                    >
                        <a-select-option v-for="(_item, _index) in scoreTypeList" :key="_index"
                            :value="_item.id"
                        >{{_item.ratingDescription}}</a-select-option>
                    </a-select> -->
                    {{item.ratingDescription}}
                </div>
                <div class="p2">{{item.description||'-'}}</div>
                <div class="p3">{{item.totalScore||'-'}}</div>
                <div class="p3">
                    <a-input-number placeholder="分数"
                        :min="0" :max="item.totalScore || 100"
                        @change="val => onScoreChange(val, index)"
                    />
                </div>
                <!-- <div class="delete" v-show="index !== 0">
                    <a-icon type="delete" class="icon" @click="onDeleteOnline(index)"/>
                </div> -->
            </div>
        </div>
        <div class="none" v-show="scoreTypeList.length === 0">没有选择评分对象或该评分对象没有可打分项</div>
        <div class="btn-cnt">
            <a-button type="primary" @click="onSubmitClick" :loading="loading">提交</a-button>
            <!-- <a-button type="primary" @click="onAddOnline" class="btn-right" v-show="formData.length < 5">新增一行</a-button> -->
        </div>
    </div>
</template>
<script>
import { getUserListByDeptId, getALLDept, addScord, getScoredTypeById } from '@/services';
import deepClone from '@/utils/deepClone';

export default {
    name: 'Score',
        data() {
        return {
            deptList: [],
            formItemLayout: {
                labelCol: { span: 6 },
                wrapperCol: { span: 16 },
            },
            formData: [{
                key: 1,
                description: '',
                totalScore: '',
                score: '',
                scoredId: null
            }],
            scoreTypeList: [],
            loading: false,
            description: '',    // 评分描述
            totalScore: '',     // 单项总分
            scoredId: '',
            scoringType: '',
        };
    },
    computed: {
        keys () {
            let arr = []
            this.formData.forEach((val, index) => {
                arr.push(index)
            })
            return arr
        }
    },
    beforeCreate() {
        this.form = this.$form.createForm(this);
    },
    mounted(){
        this.getAllList();
    },
    methods: {
        // 选择评分对象
        onDeptChange(val){
            let id;
            this.scoreTypeList = [];
            this.formData = [{
                description: '',
                totalScore: '',
                score: '',
                scoredId: ''
            }]
            if(val.length === 0) return;
            if(val.length === 1) {
                id = 0;
                this.scoredId = val[0];
                this.scoringType = 2;
            }
            else if(val.length === 2){
                id = val[1];
                this.scoredId = val[1];
                this.scoringType = 1;
            } 
            this.getScoredType(id);
        },
        // 改变评分类别
        onRuleTypeChange(val, index){
            let formData =  this.formData;
            let item = this.scoreTypeList.filter(item => item.id === val);
            formData[index].description = item[0].description;
            formData[index].totalScore = item[0].totalScore;
            formData[index].scoredId = val
            this.formData = formData;
        },
        // 获取评分类别
        async getScoredType(id, index){
            let res = await getScoredTypeById(id);
            if(res.responseObject){
                this.scoreTypeList = res.responseObject;
            }
        },
        // 打分框
        onScoreChange(val, index){
            // let formData = this.formData;
            // formData[index].score = val;
            // this.formData = formData;
            let scoreTypeList = this.scoreTypeList;
            scoreTypeList[index].score = val;
            this.scoreTypeList = scoreTypeList;
        },
        // 移除一项
        remove(index) {
            const { form } = this;
            this.formData.splice(index, 1);
            let _name = form.getFieldValue('name');
            let _score = form.getFieldValue('score');
            let _dept = form.getFieldValue('dept');
            _name.splice(index, 1);
            _score.splice(index, 1);
            _dept.splice(index, 1)
            form.setFieldsValue({
                keys: this.keys,
                dept: _dept,
                name: _name,
                score: _score
            })
        },
        // 新增一项
        add() {
            this.formData.push({
                dept: '',
                name: '',
                score: 0
            })
            const { form } = this
            form.setFieldsValue({
                keys: this.keys
            })
        },
        // 提交按钮
        handleSubmit(e) {
            e.preventDefault();
            let _that = this;
            // this.form.validateFieldsAndScroll(['name', 'score'], (err, values) => {
            //     if (!err) {
            //         const { name, score } = values;
            //         let list = [];
            //         name.map((item, index) => {
            //             if(item.length > 1) {
            //                 // 给个人打分
            //                 list.push({
            //                     scoredId: item[1],
            //                     scoringType: 1,
            //                     score: score[index]
            //                 })
            //             }else{
            //                 // 给部分打分
            //                 list.push({
            //                     scoredId: item[0],
            //                     scoringType: 2,
            //                     score: score[index]
            //                 })
            //             }
            //         })
            //         _that.onAddScore(list);
            //     }
            // })
            this.form.validateFields((err, values) => {
                if (!err) {
                    let { roleName, name, score } = values;
                    let data;
                    if(name.length > 1) {
                        data = {
                            scoredId: name[1],
                            scoringType: 1,
                            score,
                            scoredTypeId: roleName
                        }
                    }else{
                        // 给部分打分
                        data = {
                            scoredId: name[0],
                            scoringType: 2,
                            score,
                            scoredTypeId: roleName
                        }
                    }
                    _that.onAddScore([data]);
                }
            })
        },
        // 新增一行
        onAddOnline(){
            // let formData = this.formData;
            this.formData.push({
                description: '',
                totalScore: '',
                score: '',
                scoredId: ''
            })
            // this.formData = formData;
        },
        // 提交打分
        async onAddScore(params){
            this.loading = true;
            let res = await addScord(params);
            this.loading = false;
            if(res.success){
                // 提交成功后重置表单
                const _that = this;
                this.$message.success('打分成功', 1, ()=>{
                    // _that.form.resetFields();
                    // _that.formData = [{
                    //     dept: '',
                    //     name: '',
                    //     score: '',
                    // }]
                    // _that.formData = [{
                    //     key: 1,
                    //     description: '',
                    //     totalScore: '',
                    //     score: '',
                    //     scoredId: null
                    // }]
                    _that.scoreTypeList = [];
                })
            }else if(!res.success && res.errorMessage) {
                this.$message.error(res.errorMessage, 1)
            }
        },
        // 异步获取指定部门的员工列表
        async loadData(selectedOptions){
            let id = selectedOptions[0].value;
            const targetOption = selectedOptions[selectedOptions.length - 1];
            targetOption.loading = true;
            // 根据id获取该部门的所有员工
            let res = await getUserListByDeptId(id)
            targetOption.loading = false;
            if(!res.success) return;
            let _arr = res.responseObject;
            let list = [];
            _arr.map(item => 
                list.push({
                value: item.uid,
                label: item.name
            }))
            targetOption.children = list;
            this.deptList = [...this.deptList];
        },
        // 获取所有部门列表
        async getAllList(){
            let res = await getALLDept();
            if(res.success){
                // this.deptList = res.responseObject
                let list = [];
                let arr = res.responseObject;
                arr.map(item => {
                    list.push({
                        value: item.id,
                        label: item.deptname,
                        isLeaf: false,
                    })
                })
                this.deptList = list;
            }
        },
        // 提交按钮
        onSubmitClick(){
            const { scoringType, scoredId, formData, scoreTypeList } = this;
            if(!scoredId){
                this.$message.error('请先选择评分对象', 1);
                return;
            }
            if(scoreTypeList.length === 0){
                this.$message.error('请选先择评分对象并打分', 1);
                return;
            }
            if(!this.jyArr1(scoreTypeList)){
                this.$message.error('请先检查输入框', 1)
                return;
            }
            let _arr = [];
            scoreTypeList.map(item => {
                _arr.push({
                    score: item.score,
                    scoredId,
                    scoringType,
                    scoredTypeId: item.id,
                })
            })
            // console.log(_arr);
            // let _arr = [];
            // formData.map(item => {
            //     _arr.push({
            //         score: item.score,
            //         scoredId,
            //         scoringType,
            //         scoredTypeId: item.scoredId
            //     })
            // })
            // if(!this.jyArr(_arr)){
            //     this.$message.error('请先检查输入框', 1)
            //     return;
            // }
            this.onAddScore(_arr);
        },
        // 删除一行
        async onDeleteOnline(index){
            this.formData.splice(index, 1);
        },
        jyArr1(arr){
            let str = true;
            arr.map(item => {
                if(!item['score']) str = false
            })
            return str;
        },
        jyArr(arr){
            let str = true;
            arr.map(item => {
                for(let k in item){
                    if(!item[k]) str = false
                }
            })
            return str;
        }
    }
}
</script>
<style lang="less" scoped>
@color: #bfbfbf;
    .score-page{
        width: 900px;
        margin: 20px auto 0;
        .form-item0{
            margin-bottom: 0px;
            .label{
                display: inline-block;
                font-size: 16px;
            }
        }
        .form-item{
            display: inline-block;
        }
        .form-item-1{
            width: 48%;
            margin-right: 2%;
        }
        .form-item-2{
            width: 30%;
        }
        .title1{
            display: flex;
            width: 300px;
            line-height: 50px;
            height: 50px;
            border-left: 1px solid @color;
            border-top: 1px solid @color;
            margin-bottom: 20px;
            .p1{
                width: 120px;
            }
            .p2{
                width: 180px;
            }
            .p1, .p2{
                text-align: center;
                padding: 0 10px;
                border-right: 1px solid @color;
                border-bottom: 1px solid @color;
            }
        }
        .container{
            border-left: 1px solid @color;
            border-top: 1px solid @color;
            margin-bottom: 20px;
            .title{
                display: flex;
                line-height: 50px;
                height: 50px;
                position: relative;
                .delete{
                    position: absolute;
                    right: -40px;
                    .icon{
                        font-size: 20px;
                        color: red;
                        cursor: pointer;
                    }
                }
                .p1, .p2, .p3{
                    padding: 0 10px;
                    border-right: 1px solid @color;
                    border-bottom: 1px solid @color;
                    text-align: center;
                }
                .p1{
                    width: 220px;
                }
                .p2{
                    flex: 1;
                }
                .p3{
                    width: 140px;
                }
            }
        }
        .btn-cnt{
            .btn-right{
                margin-left: 15px;
            }
        }
        .none{
            width: 900px;
            text-align: center;
            margin-bottom: 20px;
        }
    }
</style>